package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SearchFeignService searchFeignService;

    private final String ZERO = "0";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        // 1、保存Spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2、保存Spu描述信息 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        // 2.1 拿到spu描述信息，并以逗号进行拆分
        List<String> decript = vo.getDecript();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3、保存Spu图片集 pms_spu_images
        List<String> imagesList = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), imagesList);

        // 4、保存Spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(item, productAttrValueEntity);
            // 4.1、设置属性名字
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            // 4.2 设置规格参数相关属性
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setAttrId(item.getAttrId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 5、保存Spu的积分信息 gulimall_sms -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        // 1、远程调用数据传输对象
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程调用优惠服务保存商品优惠信息出错");
        }
        // 5、保存当前Spu对应的所有Sku信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    // 设置默认路径
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                // 5.1 SKU的基本属性 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 5.1.1 设置sku属性
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                // 闹到保存到数据库的SkuId
                Long skuId = skuInfoEntity.getSkuId();

                // 5.2 SKU的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // true 保存 false 过滤
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 5.3 SKU的销售属性信息 pms_sku_sale_attr_value
                // 5.3.1 拿到属性集合
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    // 5.3.2 相同属性进行拷贝
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                // 5.4 SKU的优惠、满减等信息 gulimall_sms ->
                /**
                 * 5.4.1:
                 *  sms_sku_ladder = 打折信息
                 *  sms_member_price=会员价格
                 */
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 5.4.1 满几件 满减价格 不能小于0
                if (skuReductionTo.getFullCount() > 0 ||
                        skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 0) {
                    R coupon = couponFeignService.saveInfo(skuReductionTo);
                    if (coupon.getCode() != 0) {
                        log.error("保存商品优惠信息出错~~~~~~~~");
                    }
                }
            });
        }
    }

    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * 检索条件:
         *    key: '华为',//检索关键字
         *    catelogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("id", key).or().like("spu_name", key);
            });
        }
        // 验证参数是否符合条件
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !ZERO.equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !ZERO.equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String publishStatus = (String) params.get("publish_status");
        if (!StringUtils.isEmpty(catelogId) && !ZERO.equalsIgnoreCase(publishStatus)) {
            wrapper.eq("publish_status", publishStatus);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


    /**
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 1、获取到sku_info信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuBySpuId(spuId);

        // 2、取出所有的skuid
        List<Long> skuIds = skuInfoEntities.stream().map(sku -> {
            return sku.getSkuId();
        }).collect(Collectors.toList());

        // 3、拿到spu属性值
        List<ProductAttrValueEntity> attrValueEntityList = productAttrValueService.getAttrBySpuId(spuId);

        // 4、拿到属性值的属性id
        List<Long> atttrIds = attrValueEntityList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        // 5、查询出属性id中为检索属性的id
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(atttrIds);

        // 6、将为检索属性的id放到set中
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        // 7、遍历之前的spu属性集合
        List<SkuEsModel.Attrs> attrsList = attrValueEntityList.stream().filter(item -> {
            // 7.1、过滤掉不存在idSet中的属性id
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            // 7.2、将属性拷贝到To中
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        // 8、查询skuid是否存在库存，远程调用库存服务
        Map<Long, Boolean> hastockMap = null;
        try {
            R hasStock = wareFeignService.getHasStock(skuIds);
            if (hasStock.getCode() == 0) {
                // 8.1请求成功,准备封装数据类型
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
                };
                // 8.2 封装数据为Mapkey=skuid value=hasstock是否存在库存
                hastockMap = hasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            }
        } catch (Exception e) {
            log.error("远程调用库存服务出错",e);
        }

        // 9、遍历skuinfo信息，封装数据发送给搜索服务查询
        Map<Long, Boolean> finalHastockMap = hastockMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntities.stream().map(item -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            // 9.1 将skuinfo相关信息拷贝到skusmodel中
            BeanUtils.copyProperties(item, skuEsModel);
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());

            // 9.2 设置库存
            if (finalHastockMap == null) {
                skuEsModel.setHasStock(false);
            } else {
                // 9.3通过skuid验证是否有库存
                skuEsModel.setHasStock(finalHastockMap.get(item.getSkuId()));
            }
            // 9.4设置属性信息
            skuEsModel.setAttrs(attrsList);
            // TODO 商品热度频分待完善
            skuEsModel.setHotScore(0L);

            // 9.5 查询品牌名字
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            // 9.6 查询分类名称
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            return skuEsModel;
        }).collect(Collectors.toList());

        // 10、调用搜索服务，进行保存数据
        R r = searchFeignService.ProductStatusUp(skuEsModelList);
        if (r.getCode() == 0) {
            // 请求成功
            // TODO 10.1、更新spu状态为已上架，前提是es服务返回正常
            baseMapper.updateStatusSpu(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //TODO 远程调用失败？ 接口幂等性？重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long id) {
        // 根据skuid查询出skuinfo，skuinfo中包含spuid
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(id);
        // 通过skuinfo中的spuid查询到spuinfo信息
        SpuInfoEntity spuInfoEntity = getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }

    private void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }
}